<template>
  <div id="app"></div>
</template>

<script>
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
// import MapboxLanguage from '@mapbox/mapbox-gl-language';
import { getHistoryData } from '../api/historyData';
const COLOR_LEVEL = [
  'rgba(0,255,0,1)',
  'rgb(255,255,255)',
  'rgb(255,125,0)',
  'rgb(255,0,0)',
  'rgb(152,0,75)',
  'rgb(178,24,43)',
];
export default {
  data() {
    return {
      // 历史数据
      historyData: null,
      // map 地图对象实例
      map: null,
    };
  },
  beforeCreate() {
    // 兼容旧版本没有remove()的情况
    if (!('remove' in Element.prototype)) {
      Element.prototype.remove = function () {
        if (this.parentNode) {
          this.parentNode.removeChild(this);
        }
      };
    }
  },
  mounted() {
    this._createBaseMap();
  },
  methods: {
    _createBaseMap() {
      mapboxgl.accessToken =
        'pk.eyJ1IjoiaW54bG54IiwiYSI6ImNsMzRmZDE4dTBhOWczaWs3a2psanphMnUifQ.iKIlYhNlW_13OqBJLOc9sw';

      const map = new mapboxgl.Map({
        container: 'app',
        //自己绘制的样式地图令牌
        antialias: true, //抗锯齿
        style: 'mapbox://styles/mapbox/dark-v10',
        center: [113.97923191113188, 22.589860256941634],
        zoom: 12,
      });

      this.map = map;
      window.map = map;

      console.time('fetchData');
      // 请求获取关于点的一些数据
      getHistoryData().then((result) => {
        console.log('result :>> ', result);
        // 将点稀释一半
        result.features = result.features.filter((item, index) => {
          if (index % 2 === 0) return item;
        });

        let minPM2D5 = result.features[0].properties.PM2D5;
        let maxPM2D5 = result.features[0].properties.PM2D5;

        result.features.forEach((item) => {
          if (item.properties.PM2D5 < minPM2D5) {
            minPM2D5 = item.properties.PM2D5;
          }
          if (item.properties.PM2D5 > maxPM2D5) {
            maxPM2D5 = item.properties.PM2D5;
          }
        });

        console.log('minPM2D5 :>> ', minPM2D5);
        console.log('maxPM2D5 :>> ', maxPM2D5);

        this.historyData = Object.freeze(result);
        console.timeEnd('fetchData');

        // zoom变化时打印zoom值
        map.on('zoom', function (e) {
          console.log('zoom :>> ', e.target.getZoom());
        });

        this.map.on('load', () => {
          console.log('this.historyData :>> ', this.historyData);

          // 加载数据
          this.map.addSource('historyDataId', {
            type: 'geojson',
            data: this.historyData,
          });

          this.map.addLayer({
            id: 'heat-map-layer',
            type: 'heatmap',
            source: 'historyDataId',
            paint: {
              // Increase the heatmap weight based on frequency and property magnitude
              'heatmap-weight': [
                'interpolate',
                ['linear'],
                ['get', 'PM2D5'],
                0,
                ['/', ['get', 'PM2D5'], 1000],
                500,
                ['/', ['get', 'PM2D5'], 20],
              ],
              // Increase the heatmap color weight weight by zoom level
              // heatmap-intensity is a multiplier on top of heatmap-weight
              'heatmap-intensity': [
                'interpolate',
                ['linear'],
                ['zoom'],
                0,
                0.1,
                11,
                1,
              ],
              // Color ramp for heatmap.  Domain is 0 (low) to 1 (high).
              // Begin color ramp at 0-stop with a 0-transparancy color
              // to create a blur-like effect.
              'heatmap-color': [
                'interpolate',
                ['linear'],
                ['heatmap-density'],
                0,
                'rgba(0,255,0,0)',
                0.2,
                COLOR_LEVEL[0],
                0.4,
                COLOR_LEVEL[1],
                0.6,
                COLOR_LEVEL[2],
                0.8,
                COLOR_LEVEL[3],
                1,
                COLOR_LEVEL[4],
              ],
              // Adjust the heatmap radius by zoom level
              'heatmap-radius': [
                'interpolate',
                ['linear'],
                ['zoom'],
                0,
                1,
                9,
                5,
                11,
                7,
              ],
              // Transition from heatmap to circle layer by zoom level
              'heatmap-opacity': [
                'interpolate',
                ['linear'],
                ['zoom'],
                9.5,
                0,
                11,
                1,
              ],
            },
          });

          window.setFilter = () => {
            const filters = ['<=', 'pm2D5', 200];
            this.map.setFilter('heat-map-layer', filters);
          };
        });
      });
    },

    // 飞向指定的经纬度
    flyToStore(currentFeature, zoom = 15) {
      this.map.flyTo({
        center: currentFeature.geometry.coordinates,
        zoom,
        speed: 1,
      });
    },

    // 创建了一个弹出层
    createPopUp(currentFeature, contentHTML = `<h1>这是一个弹出层</h1>`) {
      const popUps = document.getElementsByClassName('mapboxgl-popup');
      // 我们需要检查并移除已经存在的弹出窗口
      if (popUps[0]) popUps[0].remove();

      new mapboxgl.Popup({ closeButton: true })
        .setLngLat(currentFeature.geometry.coordinates)
        // .setHTML(
        //   '<h3>PM2.5</h3>' +
        //     '<h4>' +
        //     'PM2.5: ' +
        //     currentFeature.properties['PM2.5'] +
        //     '</h4>'
        // )
        .setHTML(contentHTML)
        .addTo(this.map);
    },
  },
  beforeDestroy() {
    // this.map.removeLayer('historyPoints');
    this.map.remove();
  },
};
</script>

<style>
body {
  padding: 0;
  margin: 0;
  overflow: hidden;
}
#app {
  position: absolute;
  width: 100%;
  top: 0;
  bottom: 0;
}
/* 将底部的logo和信息声明隐藏 */
.mapboxgl-ctrl-logo {
  display: none !important;
}
.mapboxgl-ctrl-bottom-right {
  display: none !important;
}
/* 弹出层样式 */
.mapboxgl-popup {
  padding-bottom: 5px;
}
/* 控制关闭按钮 */
.mapboxgl-popup-close-button {
  /* display: none; */
}
.mapboxgl-popup-content {
  font: 400 15px/22px 'Source Sans Pro', 'Helvetica Neue', Sans-serif;
  padding: 0;
  width: 180px;
}
.mapboxgl-popup-content-wrapper {
  padding: 1%;
}
.mapboxgl-popup-content h3 {
  background: #91c949;
  color: #fff;
  margin: 0;
  display: block;
  padding: 10px;
  border-radius: 3px 3px 0 0;
  font-weight: 700;
  /* margin-top: -15px; */
}
.mapboxgl-popup-content h4 {
  margin: 0;
  display: block;
  padding: 10px;
  font-weight: 400;
}
.mapboxgl-popup-content div {
  padding: 10px;
}
.mapboxgl-container .leaflet-marker-icon {
  cursor: pointer;
}
.mapboxgl-popup-anchor-top > .mapboxgl-popup-content {
  margin-top: 15px;
}
.mapboxgl-popup-anchor-top > .mapboxgl-popup-tip {
  border-bottom-color: #91c949;
}
</style>
